package com.yl.immodule.v

import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.android.yl.ylicpsdk.ICPRtcManager
import com.camera.base.util.YLIMConfig
import com.camera.base.v.BaseActivity
import com.camera.routemodule.RouterPath
import com.hm.poc.IPocEngineEventHandler
import com.unionbroad.greendao.User
import com.yl.immodule.R
import com.yl.immodule.adapter.ContactsAdapter
import com.yl.immodule.databinding.ActivityChannelMembersBinding
import com.yl.immodule.v.models.ChannelMembersViewModel
import com.yl.immodule.widget.ContactActionsPopup

@Route(path = RouterPath.path.channel_members_activity)
class ChannelMembersActivity : BaseActivity<ActivityChannelMembersBinding, ChannelMembersViewModel>(), 
        ContactsAdapter.ContactClickListener, 
        ContactActionsPopup.ActionListener, 
        ContactActionsPopup.PopupStateListener {

    private val TAG = "ChannelMembersActivity"
    private lateinit var contactsAdapter: ContactsAdapter
    private var actionsPopup: ContactActionsPopup? = null
    private val mainHandler = Handler(Looper.getMainLooper())
    private var originalPaddingBottom = 0 // 保存RecyclerView原始的底部padding

    override fun getLayoutId(): Int = R.layout.activity_channel_members
    override fun getStatusBarColor(): Int = R.color.title_background_color

    override val viewModelClass: Class<ChannelMembersViewModel> = ChannelMembersViewModel::class.java

    override fun initView() {
        setupRecyclerView()
        setupSwipeRefresh()
        setupContactActionsPopup()
        setupObservers()
        
        // 保存原始的底部padding
        originalPaddingBottom = mBinding.recyclerView.paddingBottom
    }

    override fun loadData() {
        viewModel.loadChannelMembers()
    }

    private fun setupObservers() {
        viewModel.membersList.observe(this) { members ->
            if (members != null && members.isNotEmpty()) {
                mainHandler.post {
                    val newList = ArrayList(members) // 创建新的列表实例
                    contactsAdapter.submitList(newList) // 提交新列表到adapter
                    mBinding.tvEmptyState.visibility = View.GONE
                }
            } else {
                mainHandler.post {
                    contactsAdapter.submitList(emptyList())
                    mBinding.tvEmptyState.visibility = View.VISIBLE
                }
            }
            
            // 完成数据加载后停止刷新
            if (mBinding.swipeRefresh.isRefreshing) {
                mBinding.swipeRefresh.isRefreshing = false
            }
        }
    }

    private fun setupRecyclerView() {
        contactsAdapter = ContactsAdapter(this)
        mBinding.recyclerView.apply {
            layoutManager = LinearLayoutManager(this@ChannelMembersActivity)
            itemAnimator = DefaultItemAnimator()
            adapter = contactsAdapter
        }
    }

    private fun setupSwipeRefresh() {
        mBinding.swipeRefresh.setOnRefreshListener {
            viewModel.loadChannelMembers()
        }
    }
    
    private fun setupContactActionsPopup() {
        actionsPopup = ContactActionsPopup(this, this)
        actionsPopup?.setPopupStateListener(this)
    }
    
    override fun onContactClick(user: User) {
        if (ICPRtcManager.getsInstance().currentUser.number == user.number) {
            return
        }
        
        // 切换选中状态
        contactsAdapter.toggleSelection(user)
        
        // 如果有选中的联系人，显示底部弹出窗
        val selectedUsers = contactsAdapter.getSelectedUsers()
        if (selectedUsers.isNotEmpty()) {
            showContactActionsPopup()
        } else {
            // 如果没有选中联系人，关闭弹窗
            actionsPopup?.takeIf { it.isShowing }?.dismiss()
        }
    }
    
    /**
     * 显示底部联系人操作弹窗
     */
    private fun showContactActionsPopup() {
        if (actionsPopup == null) {
            actionsPopup = ContactActionsPopup(this, this)
            actionsPopup?.setPopupStateListener(this)
        }
        
        // 更新选中联系人数量显示
        val selectedUsers = contactsAdapter.getSelectedUsers()
        actionsPopup?.updateSelectedCount(selectedUsers.size)
        
        // 显示弹窗，从底部弹出
        if (actionsPopup?.isShowing != true) {
            actionsPopup?.show(mBinding.root)
        }
    }
    
    override fun onAudioCallClicked() {
        val users = contactsAdapter.getSelectedUsers()
        if (users.isNullOrEmpty()) {
            return
        }
        
        val userList = ArrayList(users)
        if (userList.size == 1) {
            // 单人音频通话
            if (YLIMConfig.windowManagerChoose) {
//                MeetManger.getInstance().startMeet(
//                    applicationContext,
//                    0,
//                    userList[0].number.toString(),
//                    null,
//                    IPocEngineEventHandler.SessionType.TYPE_AUDIO_CALL,
//                    null,
//                    false
//                )
                ARouter.getInstance()
                    .build(RouterPath.path.av_pop_activity)
                    .withString("callerId", userList[0].number.toString())
                    .withInt("type", IPocEngineEventHandler.SessionType.TYPE_AUDIO_CALL)
                    .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    .withTransition(
                        com.camera.base.R.anim.slide_in_right,
                        com.camera.base.R.anim.slide_out_left
                    )
                    .navigation()
            } else {

//                    Intent intent = new Intent(application, AvActivity.class);
//                    intent.putExtra("sessionId", incomingInfo.sessionId);
//                    intent.putExtra("callerId", incomingInfo.callerId);
//                    intent.putExtra("callerName", incomingInfo.callerName);
//                    intent.putExtra("type", incomingInfo.sessionType);
//                    intent.putExtra("extra", incomingInfo.extra);
//                    intent.putExtra("isIncomingCall", true);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    application.startActivity(intent);
                ARouter.getInstance()
                    .build(RouterPath.path.av_activity)
                    .withString("callerId", userList[0].number.toString())
                    .withInt("type", IPocEngineEventHandler.SessionType.TYPE_AUDIO_CALL)
                    .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    .withTransition(
                        com.camera.base.R.anim.slide_in_right,
                        com.camera.base.R.anim.slide_out_left
                    )
                    .navigation()
//                val intent = Intent(applicationContext, AvActivity::class.java).apply {
//                    putExtra("callerId", userList[0].number.toString())
//                    putExtra("type", IPocEngineEventHandler.SessionType.TYPE_AUDIO_CALL)
//                    flags = Intent.FLAG_ACTIVITY_NEW_TASK
//                }
//                applicationContext.startActivity(intent)
            }
        } else {
            // 创建临时对讲组
            val tempChannel = ICPRtcManager.getsInstance().createTempAudioPTTChannel(userList)
            ICPRtcManager.getsInstance().joinChannel(tempChannel.channelNumber.toString())
        }
        
        contactsAdapter.clearSelection()
        // 执行操作后自动关闭弹窗
        actionsPopup?.takeIf { it.isShowing }?.dismiss()
    }
    
    override fun onVideoCallClicked() {
        val users = contactsAdapter.getSelectedUsers()
        if (users.isNullOrEmpty() || users.size > 1) {
            return
        }
        
        val userList = ArrayList(users)
        // 单人视频通话
        if (YLIMConfig.windowManagerChoose) {
//            MeetManger.getInstance().startMeet(
//                applicationContext,
//                0,
//                userList[0].number.toString(),
//                null,
//                IPocEngineEventHandler.SessionType.TYPE_VIDEO_CALL,
//                null,
//                false
//            )
            ARouter.getInstance()
                .build(RouterPath.path.av_pop_activity)
                .withString("callerId", userList[0].number.toString())
                .withInt("type", IPocEngineEventHandler.SessionType.TYPE_VIDEO_CALL)
                .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                .withTransition(
                    com.camera.base.R.anim.slide_in_right,
                    com.camera.base.R.anim.slide_out_left
                )
                .navigation()
        } else {
            ARouter.getInstance()
                .build(RouterPath.path.av_activity)
                .withString("callerId", userList[0].number.toString())
                .withInt("type", IPocEngineEventHandler.SessionType.TYPE_VIDEO_CALL)
                .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                .withTransition(
                    com.camera.base.R.anim.slide_in_right,
                    com.camera.base.R.anim.slide_out_left
                )
                .navigation()
//            val intent = Intent(applicationContext, AvActivity::class.java).apply {
//                putExtra("callerId", userList[0].number.toString())
//                putExtra("type", IPocEngineEventHandler.SessionType.TYPE_VIDEO_CALL)
//                flags = Intent.FLAG_ACTIVITY_NEW_TASK
//            }
//            applicationContext.startActivity(intent)
        }
        
        contactsAdapter.clearSelection()
        // 执行操作后自动关闭弹窗
        actionsPopup?.takeIf { it.isShowing }?.dismiss()
    }
    
    override fun onSendMessageClicked() {
        val users = contactsAdapter.getSelectedUsers()
        if (users.isNullOrEmpty()) {
            return
        }
        
        val userList = ArrayList(users)
        if (userList.size == 1) {
            // 单人消息
            val md = ICPRtcManager.getsInstance().createMessageDialogueIfNeed(userList[0])
            ChatMessageActivity.show(this, md.chat_id)
        } else {
            // 群组消息
            val md = ICPRtcManager.getsInstance().createBroadcastMessageDialogue(userList)
            Log.e(TAG, "onSendMessageClicked: 创建临时对讲组:${md.name}")
            ChatMessageActivity.show(this, md.chat_id)
        }
        
        contactsAdapter.clearSelection()
        // 执行操作后自动关闭弹窗
        actionsPopup?.takeIf { it.isShowing }?.dismiss()
    }
    
    override fun onPopupShown(height: Int) {
        // 弹窗显示时，增加RecyclerView的底部padding，防止内容被遮挡
        mBinding.recyclerView.setPadding(
            mBinding.recyclerView.paddingLeft,
            mBinding.recyclerView.paddingTop,
            mBinding.recyclerView.paddingRight,
            originalPaddingBottom + height
        )
        
        // 如果有选中的最后一个item，确保它可见
        val lastVisiblePosition = getLastVisiblePosition()
        val selectedPosition = contactsAdapter.getLastSelectedPosition()
        
        if (selectedPosition != -1 && selectedPosition > lastVisiblePosition - 3) {
            // 滚动到选中的位置，确保完全可见
            scrollToPosition(selectedPosition)
        }
    }
    
    override fun onPopupDismissed() {
        // 弹窗消失时，恢复RecyclerView的原始底部padding
        mBinding.recyclerView.setPadding(
            mBinding.recyclerView.paddingLeft,
            mBinding.recyclerView.paddingTop,
            mBinding.recyclerView.paddingRight,
            originalPaddingBottom
        )
    }
    
    /**
     * 获取当前可见的最后一个item的位置
     */
    private fun getLastVisiblePosition(): Int {
        val layoutManager = mBinding.recyclerView.layoutManager as? LinearLayoutManager
        return layoutManager?.findLastVisibleItemPosition() ?: 0
    }
    
    /**
     * 滚动到指定位置并确保完全可见
     */
    private fun scrollToPosition(position: Int) {
        val layoutManager = mBinding.recyclerView.layoutManager as? LinearLayoutManager
        layoutManager?.smoothScrollToPosition(mBinding.recyclerView, null, position)
    }
    
    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "onDestroy: 销毁视图")
        // 清除handler回调，防止内存泄漏
        mainHandler.removeCallbacksAndMessages(null)
        
        // 确保在Activity销毁时关闭弹窗，避免窗口泄漏
        actionsPopup?.takeIf { it.isShowing }?.dismiss()
    }
} 